package com.javid.study.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.javid.study.common.UserOperationInfo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Pointcut("execution( * com.javid.study.controller.*.*(..))")
    public void point() {
    }

    @Around("point()")
    public Object pointProcess(ProceedingJoinPoint joinPoint) throws Throwable {
        Long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ip = (attributes == null) ? "" : UserOperationInfo.getIpAddr(attributes.getRequest());
        String methodName = joinPoint.getSignature().toString();
        Object[] args = joinPoint.getArgs();
        String address = UserOperationInfo.getRealAddressByIP(ip);
        log.info("ip:{}, 执行方法：{}，参数：{}，结果：{}, 耗时：{}ms", address+ "-"+ip, methodName, args, proceed, System.currentTimeMillis() - start);
        return proceed;
    }
}
